package com.example.tms.controller;

import com.example.tms.bean.MoneyInfo;
import com.example.tms.bean.OfficeInfo;
import com.example.tms.bean.ReturnInfo;
import com.example.tms.bean.UserView;
import com.example.tms.mapper.MoneyMapper;
import com.example.tms.mapper.OfficeMapper;
import com.example.tms.tools.GlobalParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 办公室报账
 */
@RestController
public class OfficeController {

    private final OfficeMapper officeMapper;

    @Autowired
    public OfficeController(OfficeMapper officeMapper) {
        this.officeMapper = officeMapper;
    }
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    //查询报账信息(报账id)
    @RequestMapping(value = "office/{bgsbzid}",method = RequestMethod.GET)
    public OfficeInfo getOfficeInfo(@PathVariable String bgsbzid){
        return officeMapper.findByBgsbzid(bgsbzid);
    }

    //查询报账信息列表
    @RequestMapping(value = "office",method = RequestMethod.GET)
    public ReturnInfo getDeptInfoAll(@RequestParam(required = false, defaultValue = "") String keyname,
                                     @RequestParam(required = false, defaultValue = "") String keyvalue) {
        List<OfficeInfo> result = officeMapper.findAll((Root<OfficeInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            switch (keyname) {
                case "jsr":
                    list.add(criteriaBuilder.like(root.get("jsr").as(String.class), "%" + keyvalue + "%"));
                    break;
                case "bzr":
                    list.add(criteriaBuilder.like(root.get("bzr").as(String.class), "%" + keyvalue + "%"));
                    break;
                default:
                    break;
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class),true));
            Predicate[] p = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //新建报账信息
    @RequestMapping(value = "office",method = RequestMethod.POST)
    public List<Map<String,Object>> saveOfficeInfo(@RequestBody OfficeInfo officeInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(officeInfo.getRiqi().equals("")){
            map.put("riqi", "0");
        }
        if(officeInfo.getMingmu().equals("")){
            map.put("mingmu", "0");
        }
        if(officeInfo.getJine().equals("")|| !checkMoney(officeInfo.getJine())){
            map.put("jine", "0");
        }
        if(officeInfo.getBzr().equals("")){
            map.put("bzr", "0");
        }
        list.add(map);
        if(map.isEmpty()){
        //区分收入和支出
            if (!officeInfo.getJine().equals("")){
                Float je = Float.parseFloat(officeInfo.getJine());
                if (je >=0){
                    officeInfo.setBgssr(officeInfo.getJine());
                    officeInfo.setBgszc("0");
                }else {
                    officeInfo.setBgszc(officeInfo.getJine().substring(1, officeInfo.getJine().length()));
                    officeInfo.setBgssr("0");
                }
            }
            Subject subject = SecurityUtils.getSubject();
            UserView userView = (UserView) subject.getPrincipal();
            officeInfo.setJsr(userView.getZsxm());
            officeInfo.setLasttime(GlobalParam.getTime());
            officeInfo.setSfcz(true);
            officeMapper.save(officeInfo);
            logger.info("新建办公室报账"+officeInfo.toString());

        }
        return list;
    }

    //更新报账信息
    @RequestMapping(value = "office",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateOfficeInfo(@RequestBody OfficeInfo officeInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(officeInfo.getBgsbzid().equals("")||officeMapper.findByBgsbzid(officeInfo.getBgsbzid())==null){
            map.put("bgsbzid", "0");
        }
        if(officeInfo.getRiqi().equals("")){
            map.put("riqi", "0");
        }
        if(officeInfo.getMingmu().equals("")){
            map.put("mingmu", "0");
        }
        if(officeInfo.getJine().equals("")){
            map.put("jine", "0");
        }
        if(officeInfo.getBzr().equals("")){
            map.put("bzr", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            //区分收入和支出
            if (!officeInfo.getJine().equals("")){
                Float je = Float.parseFloat(officeInfo.getJine());
                if (je >=0){
                    officeInfo.setBgssr(officeInfo.getJine());
                    officeInfo.setBgszc("0");
                }else {
                    officeInfo.setBgszc(officeInfo.getJine().substring(1, officeInfo.getJine().length()));
                    officeInfo.setBgssr("0");
                }
            }
            officeInfo.setJsr(officeMapper.findByBgsbzid(officeInfo.getBgsbzid()).getJsr());
            officeInfo.setLasttime(GlobalParam.getTime());
            officeInfo.setSfcz(true);
            officeMapper.save(officeInfo);
            logger.info("更新办公室报账"+officeInfo.toString());

        }
        return list;
    }

    //删除报账信息（假删除 报账id）
    @RequestMapping(value = "office/{bgsbzid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteOfficeinfo(@PathVariable String bgsbzid){
        String b;
        if(bgsbzid==null||officeMapper.findByBgsbzid(bgsbzid)==null){
            b = "该办公室报账信息不存在！";
        }else{
            officeMapper.DeleteByBgsbzid(bgsbzid);
            b = "删除成功！";
            logger.info("删除办公室报账"+bgsbzid);
        }
        return ReturnInfo.info1(b);
    }
    //检查金额
    private Boolean checkMoney(String  jine){
        Boolean b = false;
        if(jine.matches("^(\\-?)\\d+(\\.\\d+)?$")){
            b = true;
        }
        return b;
    }
}
